import requests
import json
from app.config import GAODE_API

def get_weather_info(latitude, longitude, key):
    base_url = "https://restapi.amap.com/v3/weather/weatherInfo"
    params = {
        "key": key,
        "city": "110000",  # 这里可以用城市编码，不过通过经纬度获取更准确，此参数会被下面经纬度参数覆盖
        "extensions": "base",
        "output": "json",
        "location": f"{longitude},{latitude}"
    }

    try:
        response = requests.get(base_url, params=params)
        if response.status_code == 200:
            data = json.loads(response.text)
            if data['status'] == '1':
                weather_data = data['lives'][0]
                temperature = weather_data['temperature']
                weather_status = weather_data['weather']
                wind_direction = weather_data['winddirection']
                humidity = weather_data['humidity']
                # 高德此接口污染程度相关数据需要另一种请求方式且数据有限，这里暂未获取
                print(f"当前温度: {temperature}℃")
                print(f"天气状况: {weather_status}")
                print(f"风向: {wind_direction}")
                print(f"湿度: {humidity}%")
                return temperature, weather_status, wind_direction, humidity
            else:
                print(f"请求失败，原因: {data['info']}")
        else:
            print(f"请求失败，状态码: {response.status_code}")
    except Exception as e:
        print(f"发生异常: {e}")


# 请替换为你的高德地图API Key
your_api_key = GAODE_API
latitude = 39.908911
longitude = 116.407501
get_weather_info(latitude, longitude, your_api_key)
